package missObjects;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

/**
 * Handle Group writing in file and DB and reading form DB
 * 
 * @author lefuneste
 *
 */
public class RofMissObjGroup extends RofMissionObject {
	private static Logger LOGGER = Logger.getLogger("RofLogger");

	static {
		LOGGER.getUseParentHandlers();
	}
	// initFlag to init TABLE if not exists when writing the first group into DB
	private static int writeInDBCount = 0;

	/**
	 * Create a empty group object
	 */
	public RofMissObjGroup() {
		super();
		this.objectType = "Group";
		this.indexInfile = -1;
		this.mapID = null;
		this.fileID = -1;
		this.name = "";
	}

	/**
	 * Create a group from a template object previously read in a file
	 * 
	 * @param template
	 *            : object read in file
	 */
	public RofMissObjGroup(RofTemplateObject template) {
		super();
		this.objectType = template.objectType;
		this.indexInfile = template.indexInfile;
		this.mapID = template.mapID;
		this.fileID = template.fileID;
		this.name = template.name;
	}

	/**
	 * Store the group into DB
	 * 
	 * @param con
	 *            connection to DB
	 * @throws Exception
	 */
	public void storeToDB(Connection con) throws Exception {
		try {

			Statement stmt = con.createStatement();
			String sql = "INSERT OR IGNORE INTO rofGroup (name, fileID, indexInFile, mapID ) VALUES('"
					+ this.name
					+ "','"
					+ this.fileID
					+ "','"
					+ this.indexInfile + "','" + this.mapID + "');";
			stmt.executeUpdate(sql);
			writeInDBCount++;
			LOGGER.fine("Group " + this.name + "written into DB");
			stmt.close();

		} catch (Exception e) {
			LOGGER.severe(e.getClass().getName() + ": " + e.getMessage());
			throw (e);
		}
	}

	/**
	 * Retrieve a Group object from the database by using its IndexInFile and
	 * fileID
	 * 
	 * @param con
	 *            : connection to DB
	 * @param IndexInFile
	 *            : ref#1 of Group
	 * @param fileID
	 *            : ref#2 of Group
	 * @return
	 * @throws Exception
	 */
	public void readFromDB(Connection con, int indexInFile, int fileID)
			throws Exception {

		ResultSet results = null;

		try {
			Statement stmt = con.createStatement();
			String sql = "SELECT * FROM ROFGROUP" + " WHERE fileID=" + fileID
					+ " AND indexInfile=" + indexInFile + " ;";
			results = stmt.executeQuery(sql);
			this.readfromResultSet(results);

		} catch (Exception e) {
			LOGGER.severe(e.getClass().getName() + ": " + e.getMessage());
			throw (e);
		}
	}

	public String toString() {
		String results = "";
		results = this.name + ";" + this.indexInfile + ";" + this.fileID + ";"
				+ this.mapID;
		return results;
	}

	/**
	 * Read a group from a record in DB
	 * 
	 * @param reqResults
	 *            results of a DB request
	 * @return
	 * @throws SQLException
	 */
	public void readfromResultSet(ResultSet reqResults) throws SQLException {
		try {
			while (reqResults.next()) {
				this.indexInfile = reqResults.getInt("indexInFile");
				this.name = reqResults.getString("name");
				this.fileID = reqResults.getInt("fileID");
				this.mapID = reqResults.getString("mapID");
			}
		} catch (SQLException e) {
			LOGGER.severe(e.getClass().getName() + ": " + e.getMessage());
			throw (e);
		}
	}

	/**
	 * Write a group to the mission file
	 * @param path : path to the mission file
	 * @param currentIndex : index in mission file
	 * @return next index in mission file
	 * @throws IOException 
	 */
	public int writeToFile(Path path, int index) throws IOException {
		try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.ISO_8859_1,StandardOpenOption.APPEND)) {
			String line="Group\r\n"+
					"  {\r\n"+
					"  Name = "+this.name+";\r\n"+
					"  Index = "+index+";\r\n"+
					"  Desc = \"\";\r\n"+
					"";
			writer.write(line);
			index++;
			return (index);
		}
		
	}

	/**
	 * Write the group to the Mission file
	 * @param path : path of the mission file
	 * @throws IOException 
	 */
	public void writeEndToFile(Path path) throws IOException {
		// TODO Auto-generated method stub
		try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.ISO_8859_1,StandardOpenOption.APPEND)) {
			String line="\r\n"+
					"}\r\n"+
					"";
			writer.write(line);
		}
	}
}
